package com.baibei.module.stock.basic;

import android.content.Context;

import com.baibei.basic.BasicPresenterImpl;
import com.baibei.ebec.quotation.AppQuotationFilter;
import com.baibei.ebec.quotation.QuotationManager;
import com.baibei.ebec.sdk.ApiFactory;
import com.baibei.ebec.sdk.IQuotationApi;
import com.baibei.model.KLineEntry;
import com.baibei.model.MarketStatusInfo;
import com.baibei.model.TradeTimeInfo;
import com.baibei.quotation.QuotationFilter;
import com.baibei.sdk.ApiDefaultObserver;
import com.blankj.utilcode.utils.LogUtils;

import org.greenrobot.eventbus.Subscribe;

import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * K线
 * Created by ChenRui on 2017/5/19 0019 10:50.
 */
public class StockKLinePresenterImpl extends BasicPresenterImpl<StockKLineContract.View> implements StockKLineContract.Presenter {

    private Disposable mIntervalSubscriber;
    private IQuotationApi mQuotationApi;

    /**
     * 记录当前市场状态
     */
    private int mCurrentMarketStatus;

    public StockKLinePresenterImpl(Context context, StockKLineContract.View view) {
        super(context, view);
        mQuotationApi = ApiFactory.getInstance().getQuotationApi();
    }


    /**
     * 停止刷新数据
     */
    @Override
    public void stopInterval() {
        if (mIntervalSubscriber != null && !mIntervalSubscriber.isDisposed()) {
            mIntervalSubscriber.dispose();
            mIntervalSubscriber = null;
        }
    }

    @Override
    public void start() {
        super.start();
        registerMarketStatus();
    }

    @Override
    public void registerMarketStatus() {
        //通过接口获取最新的开休市状态，再通过websocket进行开休市监听
        createObservable(mQuotationApi.getTradeTimeInfo()).subscribe(new ApiDefaultObserver<TradeTimeInfo>() {
            @Override
            protected void onError(String s) {
                if (mView != null) {
                    mView.onLoadFailed(s);
                }
            }

            @Override
            protected void accept(TradeTimeInfo info) {
                //保存接口返回状态，用于比较websocket推送状态
                mCurrentMarketStatus = info.getFlag();
                if (info.getFlag() == 1) {
                    loadKLineData();
                    startInterval();
                    if (mView != null) {
                        mView.onTradeOpenTime();
                    }
                } else {
                    if (mView != null) {
                        mView.onTradeOutTime();
                    }
                }
                //注册
                QuotationFilter filter = new QuotationFilter(AppQuotationFilter.ACTION_MARKET_STATUS);
                QuotationManager.getInstance().register(StockKLinePresenterImpl.this, filter);
            }
        });
    }

    @Override
    public void unRegisterMarketStatus() {
        QuotationManager.getInstance().unregister(this);
    }

    @Subscribe
    public void onEvent(MarketStatusInfo statusInfo) {
        LogUtils.e("开休市推送", statusInfo + ";是否需要更新状态:" + (mCurrentMarketStatus != statusInfo.getStatus()) + ";by" + mView);
        //如果开休市状态一致，取消操作
        if (mCurrentMarketStatus == statusInfo.getStatus()) {
            return;
        }
        LogUtils.e("开休市推送", "状态不一致，重新改变状态");
        //如果不一致，操作
        mCurrentMarketStatus = statusInfo.getStatus();
        stopInterval();
        //开市了
        if (mCurrentMarketStatus == 1) {
            loadKLineData();
            startInterval();
            mView.onTradeOpenTime();
            return;
        }
        //休市了
        if (mView != null) {
            mView.onTradeOutTime();
        }
    }

    /**
     * 轮询刷新数据
     */
    @Override
    public void startInterval() {
        if (mIntervalSubscriber != null && !mIntervalSubscriber.isDisposed()) {
            return;
        }
        mIntervalSubscriber = Observable.interval(30, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        loadKLineData();
                    }
                });
    }


    /**
     * 加载K线数据
     */
    private void loadKLineData() {
        createObservable(mQuotationApi.getKLineForweekData(mView.getProductId(), mView.getType()))
                .subscribe(new ApiDefaultObserver<List<KLineEntry>>() {
                    @Override
                    protected void onError(String s) {
                        if (mView == null) return;
                        mView.onLoadFailed(s);
                    }

                    @Override
                    protected void accept(List<KLineEntry> kLineEntries) {
                        LogUtils.e("K线数据", ";by" + mView);
                         if (mView == null) return;
                        mView.onLoadKLineData(kLineEntries);
                    }
                });
    }

    @Override
    public void destroy() {
        unRegisterMarketStatus();
        stopInterval();
        super.destroy();
    }


}
